package cn.com.cjwsjy.monitor.platform.earlywarn.service.impl;

import cn.com.cjwsjy.monitor.platform.earlywarn.dao.EarlyWarningPlanDao;
import cn.com.cjwsjy.monitor.platform.earlywarn.dao.EngineeringsDao;
import cn.com.cjwsjy.monitor.platform.earlywarn.dao.PositionsDao;
import cn.com.cjwsjy.monitor.platform.earlywarn.entity.EarlyWarningPlanEntity;
import cn.com.cjwsjy.monitor.platform.earlywarn.entity.engineers.EngineeringsEntity;
import cn.com.cjwsjy.monitor.platform.earlywarn.entity.engineers.PositionsEntity;
import cn.com.cjwsjy.monitor.platform.earlywarn.service.EarlyWarningPlanService;
import cn.com.cjwsjy.monitor.platform.earlywarn.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EarlyWarningPlanServiceImpl implements EarlyWarningPlanService {
    @Autowired
    private EngineeringsDao engineeringsDao;

    @Autowired
    private PositionsDao positionsDao;

    @Autowired
    private EarlyWarningPlanDao earlyWarningPlanDao;


    /**
     *  获取所有工程部位，从其他微服务复制过来的代码
     *  合并到原系统后，通过openfeign直接调用 dataEarlywarnFeignService.getAllPositions();
     *
     * @return
     */
    @Override
    public R getAllPositions() {
        List<PositionsEntity> list = new ArrayList<>();
        //获取所有工程对象通过工程对象获取工程部位
        List<EngineeringsEntity> entities = engineeringsDao.selectList(null);
        for (EngineeringsEntity entity : entities) {
            PositionsEntity positionsEntity = new PositionsEntity();
            positionsEntity.setName(entity.getEngineering());
            positionsEntity.setId(entity.getId());
            List<PositionsEntity> positionsEntityList = positionsDao.selectList(new QueryWrapper<PositionsEntity>().eq("eng_id", entity.getId()));
            //找到所有一级分类（在本系统下可以说是二级）
            List<PositionsEntity> level1Menus = positionsEntityList.stream().filter(item ->
                    item.getFatherId() == null
            ).map(item -> {
                //递归获取子菜单
                item.setChildren(getChildren(item, positionsEntityList));
                return item;
            }).collect(Collectors.toList());
            //将结果集添加到list集合里面
            positionsEntity.setChildren(level1Menus);
            list.add(positionsEntity);
        }
        return R.ok().put("data",list);
    }


    /**
     * 递归获取所有子菜单
     *
     * @param root 当前菜单
     * @param all  所有菜单
     * @return
     */
    public List<PositionsEntity> getChildren(PositionsEntity root, List<PositionsEntity> all) {
        List<PositionsEntity> children = all.stream()
                .filter(item -> (item.getFatherId() == null ? 0 : item.getFatherId()) == (root.getId() == null ? 0 : root.getId()))
                .map(item -> {
                    item.setChildren(getChildren(item, all));
                    return item;
                }).collect(Collectors.toList());
        return children;
    }


    /**
     * 添加应急预案
     *
     * @param docName 文件名
     * @param warningLevel  预警等级
     * @param  applicablePeriod 适用日期
     * @param  positionName 工程部位
     * @param  file 上传文件
     * @param  uploadPerson 上传人
     * @return
     */
    @Override
    public R addPlan(String docName, String warningLevel, String applicablePeriod, String positionName, MultipartFile file, String uploadPerson) throws IOException {
        EarlyWarningPlanEntity earlyWarningPlanEntity=new EarlyWarningPlanEntity();
        earlyWarningPlanEntity.setDocName(docName);
        earlyWarningPlanEntity.setWarningLevel(warningLevel);
        earlyWarningPlanEntity.setApplicablePeriod(applicablePeriod);
        earlyWarningPlanEntity.setPositionName(positionName);
        earlyWarningPlanEntity.setUploadPerson(uploadPerson);
        //获取原始文件名
        String realFileName=file.getOriginalFilename();
        assert realFileName != null;
        //设置存放文件的磁盘路径
        String filePath="D:\\";
        File uploadFile=new File(filePath,realFileName);
        String fileStorePath=filePath+realFileName;
        //存放文件到指定路径
        FileUtils.writeByteArrayToFile(uploadFile,file.getBytes());
        //获取文件后缀名
        String suffix=realFileName.substring(realFileName.lastIndexOf(".")+1);
        earlyWarningPlanEntity.setDocType(suffix);
        //获取文件大小并转换为kb单位
        BigDecimal b= BigDecimal.valueOf(Float.parseFloat(String.valueOf(file.getSize())) / 1024);
        float size = b.setScale(2, RoundingMode.HALF_UP).floatValue();
        String fileSize = size+"kb";
        earlyWarningPlanEntity.setDocSize(fileSize);
        Date date = new Date();
        earlyWarningPlanEntity.setUploadTime(date);
        earlyWarningPlanEntity.setFilePath(fileStorePath);
        earlyWarningPlanDao.insert(earlyWarningPlanEntity);
        return R.ok();
    }
    /**
     * 获取所有已添加过的适用时期
     * @return
     */
    @Override
    public R getAllPeriods(){
        QueryWrapper<EarlyWarningPlanEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select();
        //获取数据表中所有数据
        List<EarlyWarningPlanEntity> earlyWarningPlanEntityList = earlyWarningPlanDao.selectList(queryWrapper);
        //applicationPeriodList列表存放所有的适用时期
        List<String> applicationPeriodList = new ArrayList<>();
        for(EarlyWarningPlanEntity earlyWarningPlanEntity:earlyWarningPlanEntityList){
            String applicationPeriod = earlyWarningPlanEntity.getApplicablePeriod();
            applicationPeriodList.add(applicationPeriod);
        }
        return R.ok().put("applicationPeriod",applicationPeriodList);
    }
    /**
     * 修改应急预案
     * @param  id 应急预案id
     * @param docName 文件名
     * @param warningLevel  预警等级
     * @param  applicablePeriod 适用日期
     * @param  positionName 工程部位
     * @param  file 上传文件
     * @param  uploadPerson 上传人
     * @return
     */
    @Override
    public R updatePlan( Long id, String docName, String warningLevel, String applicablePeriod, String positionName, MultipartFile file, String uploadPerson) throws IOException {
        //先删除之前存在磁盘的文件
        EarlyWarningPlanEntity oldEarlyWarningPlanEntity= earlyWarningPlanDao.selectById(id);
        String oldFilePath = oldEarlyWarningPlanEntity.getFilePath();
        File fileDelete = new File(oldFilePath);
        Boolean result = fileDelete.delete();
        System.out.println("是否成功删除之前的文件：");
        System.out.println(result);

        EarlyWarningPlanEntity earlyWarningPlanEntity=new EarlyWarningPlanEntity();
        earlyWarningPlanEntity.setId(id);
        earlyWarningPlanEntity.setDocName(docName);
        earlyWarningPlanEntity.setWarningLevel(warningLevel);
        earlyWarningPlanEntity.setApplicablePeriod(applicablePeriod);
        earlyWarningPlanEntity.setPositionName(positionName);
        earlyWarningPlanEntity.setUploadPerson(uploadPerson);
        //获取原始文件名
        String realFileName=file.getOriginalFilename();
        assert realFileName != null;
        //设置存放文件的磁盘路径
        String filePath="D:\\";
        File uploadFile=new File(filePath,realFileName);
        String fileStorePath=filePath+realFileName;
        //存放文件到指定路径
        FileUtils.writeByteArrayToFile(uploadFile,file.getBytes());
        //获取文件后缀名
        String suffix=realFileName.substring(realFileName.lastIndexOf(".")+1);
        earlyWarningPlanEntity.setDocType(suffix);
        //获取文件大小并转换为kb单位
        BigDecimal b= BigDecimal.valueOf(Float.parseFloat(String.valueOf(file.getSize())) / 1024);
        float size = b.setScale(2, RoundingMode.HALF_UP).floatValue();
        String fileSize = size+"kb";
        earlyWarningPlanEntity.setDocSize(fileSize);
        Date date = new Date();
        earlyWarningPlanEntity.setUploadTime(date);
        earlyWarningPlanEntity.setFilePath(fileStorePath);
        earlyWarningPlanDao.updateById(earlyWarningPlanEntity);
        return R.ok("更新成功");
    }

    /**
     * 删除应急预案
     *
     * @param id 应急预案id
     * @return
     */
    @Override
    public  R deletePlan(Long id){
        EarlyWarningPlanEntity earlyWarningPlanEntity= earlyWarningPlanDao.selectById(id);
        String filePath = earlyWarningPlanEntity.getFilePath();
        //删除预案中存放在磁盘的文件
        File fileDelete = new File(filePath);
        Boolean result = fileDelete.delete();
        System.out.println("是否成功删除之前的文件：");
        System.out.println(result);
        earlyWarningPlanDao.deleteById(id);
        return R.ok("删除成功");
    }


}
